<template>
    <div class="memo-container">
        <!-- 侧边栏 -->
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>备忘录</h2>
                <button @click="showNewMemoForm" class="new-memo-btn">
                    <i class="mdi mdi-plus"></i> 新建
                </button>
            </div>

            <div class="search-box">
                <input v-model="searchQuery" placeholder="搜索..." @input="filterMemos">
            </div>

            <div class="category-list">
                <div v-for="category in categories" :key="category" class="category-item"
                    :class="{ active: selectedCategory === category }" @click="selectCategory(category)">
                    {{ category }}
                </div>
            </div>

            <div class="tag-cloud">
                <h3>标签</h3>
                <div class="tags">
                    <span v-for="tag in allTags" :key="tag" class="tag" :class="{ active: selectedTags.includes(tag) }"
                        @click="toggleTag(tag)">
                        {{ tag }}
                    </span>
                </div>
            </div>
        </div>

        <!-- 主内容区 -->
        <div class="main-content">
            <!-- 备忘录列表 -->
            <div class="memo-list" v-if="!showEditor">
                <div v-for="memo in filteredMemos" :key="memo.id" class="memo-item"
                    :class="{ active: activeMemo?.id === memo.id }" @click="selectMemo(memo)">
                    <div class="memo-header">
                        <h3>{{ memo.title || '无标题' }}</h3>
                        <button @click.stop="deleteMemo(memo.id)" class="delete-btn">
                            <i class="mdi mdi-trash-can-outline"></i>
                        </button>
                    </div>
                    <p class="preview">{{ getPreview(memo.content) }}</p>
                    <div class="memo-footer">
                        <span class="date">{{ formatDate(memo.updatedAt) }}</span>
                        <div class="tags">
                            <span v-for="tag in memo.tags" class="tag">{{ tag }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 编辑器 -->
            <div class="memo-editor" v-else>
                <div class="editor-header">
                    <input v-model="currentMemo.title" placeholder="输入标题" class="title-input">
                    <div class="editor-toolbar">
                        <select v-model="currentMemo.category" class="category-select">
                            <option v-for="category in categories" :value="category" :key="category">
                                {{ category }}
                            </option>
                        </select>
                        <input v-model="newTag" placeholder="添加标签" @keyup.enter="addTag" class="tag-input">
                    </div>
                </div>

                <textarea v-model="currentMemo.content" placeholder="输入内容..." class="content-editor"></textarea>

                <div class="editor-footer">
                    <div class="tags">
                        <span v-for="(tag, index) in currentMemo.tags" :key="index" class="tag">
                            {{ tag }}
                            <i class="mdi mdi-close" @click="removeTag(index)"></i>
                        </span>
                    </div>
                    <div class="actions">
                        <button @click="cancelEdit" class="cancel-btn">取消</button>
                        <button @click="saveMemo" class="save-btn">保存</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>

import { DeleteMemo, LoadCategories, LoadMemos, SaveMemo } from '../../wailsjs/go/controller/MemoApp'

export default {
    data() {
        return {
            memos: [],
            categories: ['工作', '个人', '学习'],
            allTags: [],
            searchQuery: '',
            selectedCategory: 'all',
            selectedTags: [],
            activeMemo: null,
            currentMemo: this.createEmptyMemo(),
            showEditor: false,
            newTag: ''
        }
    },

    computed: {
        filteredMemos() {
            return this.memos.filter(memo => {
                // 分类筛选
                const categoryMatch = this.selectedCategory === 'all' ||
                    memo.category === this.selectedCategory

                // 标签筛选
                const tagMatch = this.selectedTags.length === 0 ||
                    this.selectedTags.some(tag => memo.tags.includes(tag))

                // 搜索筛选
                const searchMatch = this.searchQuery === '' ||
                    memo.title.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
                    memo.content.toLowerCase().includes(this.searchQuery.toLowerCase())

                return categoryMatch && tagMatch && searchMatch
            }).sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
        }
    },

    async created() {
        await this.loadMemos()
        this.extractAllTags()
    },

    methods: {
        createEmptyMemo() {
            return {
                id: null,
                title: '',
                content: '',
                tags: [],
                category: '工作',
                createdAt: new Date(),
                updatedAt: new Date()
            }
        },

        async loadMemos() {
            try {
                this.memos = await LoadMemos() || []
            } catch (error) {
                console.error('加载备忘录失败:', error)
            }
        },

        extractAllTags() {
            const tags = new Set()
            this.memos.forEach(memo => {
                memo.tags.forEach(tag => tags.add(tag))
            })
            this.allTags = Array.from(tags)
        },

        getPreview(content) {
            return content.length > 100
                ? content.substring(0, 100) + '...'
                : content || '无内容'
        },

        formatDate(date) {
            return new Date(date).toLocaleDateString()
        },

        selectCategory(category) {
            this.selectedCategory = category
            this.activeMemo = null
        },

        toggleTag(tag) {
            const index = this.selectedTags.indexOf(tag)
            if (index === -1) {
                this.selectedTags.push(tag)
            } else {
                this.selectedTags.splice(index, 1)
            }
            this.activeMemo = null
        },

        selectMemo(memo) {
            this.activeMemo = memo
            this.currentMemo = { ...memo }
            this.showEditor = true
        },

        showNewMemoForm() {
            this.currentMemo = this.createEmptyMemo()
            this.currentMemo.id = Date.now().toString()
            this.showEditor = true
            this.activeMemo = null
        },

        addTag() {
            if (this.newTag.trim() && !this.currentMemo.tags.includes(this.newTag.trim())) {
                this.currentMemo.tags.push(this.newTag.trim())
                this.newTag = ''
            }
        },

        removeTag(index) {
            this.currentMemo.tags.splice(index, 1)
        },

        cancelEdit() {
            this.showEditor = false
            this.currentMemo = this.createEmptyMemo()
        },

        async saveMemo() {
            try {
                // 防御性编程 - 检查currentMemo是否存在
                if (!this.currentMemo) {
                    console.error('保存失败: currentMemo为null')
                    this.showNotification('保存失败', '当前备忘录为空', 'error')
                    this.currentMemo = this.createEmptyMemo()
                    return
                }

                // 确保有ID
                if (!this.currentMemo.id) {
                    this.currentMemo.id = Date.now().toString()
                    console.log('为新备忘录生成ID:', this.currentMemo.id)
                }

                // 设置更新时间
                this.currentMemo.updatedAt = new Date()

                // 如果是新备忘录，设置创建时间
                if (!this.currentMemo.createdAt) {
                    this.currentMemo.createdAt = new Date()
                }

                // 显示保存状态
                this.isSaving = true

                // 调用后端保存
                console.log('正在保存备忘录:', JSON.stringify(this.currentMemo, null, 2))
                const savedMemo = await SaveMemo(this.currentMemo)
                console.log('保存返回:', savedMemo)

                // 验证返回结果
                if (!savedMemo || !savedMemo.id) {
                    throw new Error('后端返回无效的备忘录数据')
                }

                // 更新前端列表
                const index = this.memos.findIndex(m => m.id === savedMemo.id)
                if (index === -1) {
                    this.memos.unshift(savedMemo)
                } else {
                    this.memos.splice(index, 1, savedMemo)
                }

                // 更新标签云
                this.extractAllTags()

                // 重置状态
                this.showEditor = false
                this.currentMemo = this.createEmptyMemo()

                // 显示成功通知
                this.showNotification('保存成功', '备忘录已保存', 'success')

            } catch (error) {
                console.error('保存备忘录失败:', error)
                this.showNotification('保存失败', error.message || '保存备忘录时出错', 'error')

            } finally {
                this.isSaving = false
            }
        },
        showNotification(title, message, type) {
            if (type === 'success') {
                this.$notify.success({
                    title: title,
                    message: message
                })
            } else if (type === 'error') {
                this.$notify.error({
                    title: title,
                    message: message
                })
            }
        },
        async deleteMemo(id) {
            try {
                await DeleteMemo(id)
                this.memos = this.memos.filter(memo => memo.id !== id)
                this.extractAllTags()

                if (this.activeMemo?.id === id) {
                    this.activeMemo = null
                    this.showEditor = false
                }
            } catch (error) {
                console.error('删除备忘录失败:', error)
            }
        }
    }
}
</script>

<style scoped>
.memo-container {
    display: flex;
    height: 100vh;
    font-family: 'Arial', sans-serif;
}

/* 侧边栏样式 */
.sidebar {
    width: 250px;
    background-color: #2d3748;
    color: white;
    padding: 20px;
    display: flex;
    flex-direction: column;
}

.sidebar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.sidebar-header h2 {
    margin: 0;
    font-size: 1.5rem;
}

.new-memo-btn {
    background-color: #4a6cf7;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 5px 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 5px;
}

.search-box {
    margin-bottom: 20px;
}

.search-box input {
    width: 100%;
    padding: 8px;
    border-radius: 4px;
    border: none;
    background-color: #4a5568;
    color: white;
}

.category-list {
    margin-bottom: 20px;
}

.category-item {
    padding: 10px;
    cursor: pointer;
    border-radius: 4px;
    margin-bottom: 5px;
}

.category-item:hover {
    background-color: #4a5568;
}

.category-item.active {
    background-color: #4a6cf7;
}

.tag-cloud {
    margin-top: auto;
}

.tag-cloud h3 {
    margin-bottom: 10px;
    font-size: 1rem;
    color: #a0aec0;
}

.tags {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.tag {
    background-color: #4a5568;
    color: white;
    padding: 3px 8px;
    border-radius: 4px;
    font-size: 0.8rem;
    cursor: pointer;
}

.tag.active {
    background-color: #4a6cf7;
}

/* 主内容区样式 */
.main-content {
    flex: 1;
    display: flex;
    overflow: hidden;
}

.memo-list {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background-color: #f7fafc;
}

.memo-item {
    background-color: white;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    cursor: pointer;
}

.memo-item.active {
    border-left: 3px solid #4a6cf7;
}

.memo-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.memo-header h3 {
    margin: 0;
    font-size: 1.1rem;
    color: #2d3748;
}

.delete-btn {
    background: none;
    border: none;
    color: #a0aec0;
    cursor: pointer;
}

.preview {
    color: #718096;
    margin-bottom: 10px;
    font-size: 0.9rem;
    line-height: 1.4;
}

.memo-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 0.8rem;
    color: #a0aec0;
}

.memo-footer .tags {
    display: flex;
    gap: 5px;
}

/* 编辑器样式 */
.memo-editor {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 20px;
    background-color: white;
}

.editor-header {
    margin-bottom: 20px;
}

.title-input {
    width: 100%;
    font-size: 1.5rem;
    border: none;
    border-bottom: 1px solid #e2e8f0;
    padding: 10px 0;
    margin-bottom: 15px;
    outline: none;
}

.editor-toolbar {
    display: flex;
    gap: 10px;
    align-items: center;
}

.category-select {
    padding: 5px;
    border-radius: 4px;
    border: 1px solid #e2e8f0;
}

.tag-input {
    padding: 5px;
    border-radius: 4px;
    border: 1px solid #e2e8f0;
    flex: 1;
}

.content-editor {
    flex: 1;
    border: none;
    outline: none;
    resize: none;
    font-size: 1rem;
    line-height: 1.6;
    padding: 10px;
    margin-bottom: 15px;
}

.editor-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 15px;
    border-top: 1px solid #e2e8f0;
}

.editor-footer .tags {
    display: flex;
    gap: 5px;
}

.editor-footer .tag {
    display: flex;
    align-items: center;
    gap: 3px;
}

.actions {
    display: flex;
    gap: 10px;
}

.cancel-btn {
    background-color: #e2e8f0;
    color: #4a5568;
    border: none;
    border-radius: 4px;
    padding: 8px 15px;
    cursor: pointer;
}

.save-btn {
    background-color: #4a6cf7;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 8px 15px;
    cursor: pointer;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .memo-container {
        flex-direction: column;
    }

    .sidebar {
        width: 100%;
        height: auto;
    }

    .main-content {
        flex-direction: column;
    }

    .memo-list,
    .memo-editor {
        min-height: 50vh;
    }
}
</style>